/*-- Includes --*/

#include "messages.h"
#include "basicas.h"

/***********************************************************
 *
 *	Envia un mensaje al socket pasado como parametro
 *
 ***********************************************************/
int sendMessage(int socket, char* message){

	int messageSize, sendReturnMessageSize;
	char logMessageAux[255];

	messageSize = strlen(message);
	sendReturnMessageSize = send(socket, message, messageSize, 0);

	if( sendReturnMessageSize == messageSize ){
		message[0] = 'T';
		sprintf(logMessageAux, "[OK] Mensaje Enviado [%d] [%s] (tamanio %d)", socket, message, messageSize);
		setLogAdp(logMessageAux, INFO);
		return SEND_MESSAGE_OK;
	}

	return SEND_MESSAGE_ERROR;
}


/*******************************************
 *
 *******************************************/
int receiveMessage(int socket, char* messageToReceive){

	char charWithMessageSize;
	int receiveReturnValue;
	char charAux[60];
	char receiveMessageAux[60];

	/* leemos el primer caracter */
	receiveReturnValue = recv(socket, &charWithMessageSize, 1, 0);

	switch (receiveReturnValue){
		case 1:

			/*-- Recibio el 1er byte bien --*/
			sprintf(charAux,"tamanio total del mensaje: %d",(int)charWithMessageSize);
			/* setLog(charAux,INFO,NOMBREPROCESO); */
			/* printf(" Se leyo primer caracter: tamanio = %d\n", (int)charWithMessageSize); */
			break;
		
		case 0:

			/*-- EOF or Connection Closed --*/
			strcpy(messageToReceive, "ConnectionClosed"); /* automensaje */
			/* printf("2 - messageToReceive %s \n", messageToReceive); */
			return 0;
			break;
		
		case -1:

			/*-- Something wrong --*/
			strcpy(messageToReceive, "ERROR");
			return 0;
			break;
	}

	memset(receiveMessageAux,'\0', sizeof(receiveMessageAux));
	receiveReturnValue = recv(socket, receiveMessageAux, (charWithMessageSize-1), 0);
	/* printf("Recibio resto: %s\n", receiveMessageAux); */

	sprintf(charAux,"%d bytes recibidos en total",(int)receiveReturnValue+1);

	if (receiveReturnValue==(charWithMessageSize-1)){
		/*setLog("recepcion finalizada correctamente",INFO,NOMBREPROCESO);*/
		receiveMessageAux[receiveReturnValue]='\0';
		strcpy(messageToReceive,receiveMessageAux);
		/* printf("messageToReceive > 1 : %s \n",receiveMessageAux); */
		return 1;
	}else{
		
		strcpy(messageToReceive,"ERROR");
		printf(" messageToReceive %d ERROR\n", receiveReturnValue);

		return 0;
	}
	
	printf("receiveReturnValue es: %d\n", receiveReturnValue);
	return 0;
}
